#!/bin/zsh
set -e

FRAMEWORK_BINARY="${BUILT_PRODUCTS_DIR}/demo.framework/demo"
DYLIB_OUTPUT="${BUILT_PRODUCTS_DIR}/libdemo_ios.dylib"
echo "input file: $FRAMEWORK_BINARY"

# set target platform
if [ "${PLATFORM_NAME}" = "iphonesimulator" ]; then
    PLATFORM_ARG="ios-sim"
elif [ "${PLATFORM_NAME}" = "iphoneos" ]; then
    PLATFORM_ARG="ios"
fi
# copy and rename
cp -vf "$FRAMEWORK_BINARY" "$DYLIB_OUTPUT" || exit 1

# change dylib rpath
install_name_tool -id "@rpath/libdemo_ios.dylib" "$DYLIB_OUTPUT" || {
    echo "install_name_tool failed" >&2
    exit 1
}

# compile cangjie
PACKAGE_PATH="${PROJECT_DIR}/../../package"
TYPE="debug"
if [[ "$CONFIGURATION" == "Release" ]]; then
    TYPE="release"
fi
bash ${PACKAGE_PATH}/build.sh ${TYPE} "$PLATFORM_ARG"
# change cangjie dylib rpath
cangjie_dylib_path="${PROJECT_DIR}/libs/libdemo.dylib"
# codesign --remove-signature $cangjie_dylib_path
install_name_tool -change @rpath/libdemo_ios.dylib @rpath/demo.framework/demo $cangjie_dylib_path

# embed and sign
export PATH="/opt/homebrew/opt/ruby/bin:$PATH"
export GEM_HOME="$(gem env home)"
export GEM_PATH="$(gem env path)"
ruby embed-libraries.rb "${PROJECT_DIR}" "${TARGET_NAME}"
